#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>

#include "StdTcp.h"


StdTcpServer::StdTcpServer(const char *ip, unsigned short port)
{

    sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock < 0)
    {
        perror("socket");
        return;
    }

    //设置端口复用,防止出现bind绑定
    int use = 1;
    setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&use,sizeof(use));

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip);
    if(bind(sock,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("bind");
        close(sock);
        return;
    }

    //最大等待队列,连接确立
    if(listen(sock,10) < 0)
    {
        perror("listen");
        close(sock);
        return;
    }
}

int StdTcpServer::Accept()
{
    struct sockaddr_in ClientAddr;
    socklen_t len = sizeof(ClientAddr);
    //清除已经建立连接的客户端队列，以便服务器处理后续握手
    int clientSock = accept(sock,(struct sockaddr*)&ClientAddr,&len);
    printf("连接进来的客户端socket:%d,地址:%s 端口:%d\n",
        clientSock,inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port));
    return clientSock;
}

bool StdTcpServer::TcpServerRecv(int clientSock, void *ptr, size_t size)
{
    if(recv(clientSock,ptr,size,0) <= 0)
        return false;
    else
        return true;
}

bool StdTcpServer::TcpServerSend(int clientSock, void *ptr, size_t size)
{
    if(send(clientSock,ptr,size,0) <= 0)
        return false;
    else
        return true;
}

StdTcpServer::~StdTcpServer()
{
    close(sock);
}






StdTcpClient::StdTcpClient(const char *ServerIP, unsigned short ServerPort)
{
 
    sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock < 0)
    {
        perror("socket");
        return;
    }
    
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(ServerPort);
    addr.sin_addr.s_addr = inet_addr(ServerIP);

    //连接函数
    if(connect(sock,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("connect");
        close(sock);
        return;
    }
}

bool StdTcpClient::TcpClientRecv(void *ptr, size_t size)
{
    if(recv(sock,ptr,size,0) <= 0)
        return false;
    else
        return true;
}

bool StdTcpClient::TcpClientSend(void *ptr, size_t size)
{
    if(send(sock,ptr,size,0) <= 0)
        return false;
    else
        return true;
}

StdTcpClient::~StdTcpClient()
{
    close(sock);
}
